<script setup lang="ts">
import { FormSchema, Form } from '@/components/Form'
import { ElDrawer } from 'element-plus'
import { PropType, reactive, watch } from 'vue'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { DictPageResponse } from '@/api/dict/types'

const props = defineProps({
  type: {
    type: String as PropType<'add' | 'edit'>,
    default: 'add',
    validator: (val: string) => ['add', 'edit'].includes(val)
  },
  row: {
    type: Object as PropType<DictPageResponse>,
    default: () => ({})
  }
})

const { t } = useI18n()

const modelValue = defineModel<boolean>()

const { required } = useValidator()

const formSchema = reactive<FormSchema[]>([
  {
    field: 'label',
    label: t('dict.itemName'),
    component: 'Input',
    colProps: {
      span: 24
    }
  },
  {
    field: 'value',
    label: t('dict.itemCode'),
    component: 'Input',
    colProps: {
      span: 24
    }
  },
  {
    field: 'status',
    label: t('common.status'),
    value: true,
    component: 'Switch',
    colProps: {
      span: 24
    }
  }
])

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose, setValues } = formMethods

const emit = defineEmits(['confirm'])

const rules = reactive({
  label: [required()],
  value: [required()]
})

const confirm = async () => {
  const elFormExpose = await getElFormExpose()
  if (!elFormExpose) return
  const valid = await elFormExpose?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    emit('confirm', formData)
    modelValue.value = false
  }
}

watch(
  () => props.row,
  (value: any) => {
    setValues(value)
  },
  {
    deep: true
  }
)
</script>

<template>
  <ElDrawer
    :destroy-on-close="true"
    v-model="modelValue"
    :title="(type === 'add' ? t('common.add') : t('common.edit')) + ' ' + t('dict.item')"
  >
    <template #default>
      <Form :rules="rules" @register="formRegister" :schema="formSchema" />
    </template>
    <template #footer>
      <div>
        <BaseButton @click="() => (modelValue = false)">{{ t('common.close') }}</BaseButton>
        <BaseButton type="primary" @click="confirm">{{ t('common.save') }}</BaseButton>
      </div>
    </template>
  </ElDrawer>
</template>
